# coding = utf-8
import datetime

from case.models import Case, Letter, Introduce, Progress, CaseProgress, Reason, CriminalIntroduce, CaseFile
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer


class IntroduceSerializer(ModelSerializer):
    """
    介绍信
    """
    case_name = serializers.CharField(source="case.code", read_only=True)
    case_type = serializers.CharField(source="case.case_type", read_only=True)
    user_name = serializers.CharField(source="user.real_name", read_only=True)

    class Meta:
        model = Introduce
        exclude = ['update_time', 'add_time']


class LetterSerializer(ModelSerializer):
    """
    律所函
    """
    case_name = serializers.CharField(source="case.code", read_only=True)
    case_type = serializers.CharField(source="case.case_type", read_only=True)
    user_name = serializers.CharField(source="user.real_name", read_only=True)

    class Meta:
        model = Letter
        exclude = ['update_time', 'add_time']


class ProgressParentSerializer(ModelSerializer):
    """案件进展配置"""
    children = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Progress
        fields = ['id', 'name', 'children']

    def get_children(self, obj):
        if obj.children.count() == 0:
            return None
        return self.__class__(obj.children.all(), many=True).data


class ProgressSerializer(ModelSerializer):
    """案件进展配置"""
    # progress_time = serializers.SerializerMethodField()  # 设置时间
    children = serializers.SerializerMethodField(read_only=True)
    final_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Progress
        exclude = ['update_time', 'add_time']

    def get_final_name(self, obj):
        if obj.is_final:
            return "结案"
        else:
            return "  "
    # def get_progress_time(self, obj):
    #     request = self.context["request"]
    #     if request:
    #         case_id = request.query_params.get("case_id", None)
    #         progress = CaseProgress.objects.filter(case_id=case_id, progress_id=obj.id).first()
    #         if progress:
    #             return progress.add_time
    #         return None
    #     return None

    def get_children(self, obj):
        if obj.children.count() == 0:
            return None

        return self.__class__(obj.children.all(), many=True).data


class CaseProgressSerializer(ModelSerializer):
    """案件进展"""

    progress_name = serializers.CharField(source="progress.name", read_only=True)
    add_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
    confirm_name = serializers.CharField(source='get_confirm_display', read_only=True)

    class Meta:
        model = CaseProgress
        exclude = ['update_time']


class CaseFileSerializer(ModelSerializer):
    """案件资料"""

    class Meta:
        model = CaseFile
        exclude = ['update_time', 'add_time']


class CaseSimpleSerializer(ModelSerializer):
    """
    案件登记
    """
    case_type_name = serializers.CharField(source="get_case_type_display", read_only=True)
    user_name = serializers.CharField(source="user.real_name", read_only=True)
    lead_lawyer_name = serializers.CharField(source="lead_lawyer.real_name", read_only=True)
    assist_lawyer_name = serializers.CharField(source="assist_lawyer.real_name", read_only=True)
    third_lawyer_name = serializers.CharField(source="third_lawyer.real_name", read_only=True)

    class Meta:
        model = Case
        exclude = ['recv_time', 'update_time', 'add_time']


class CaseSerializer(ModelSerializer):
    """
    案件登记
    """
    case_type_name = serializers.CharField(source="get_case_type_display", read_only=True)
    user_name = serializers.CharField(source="user.real_name", read_only=True)
    lead_lawyer_name = serializers.CharField(source="lead_lawyer.real_name", read_only=True)
    assist_lawyer_name = serializers.CharField(source="assist_lawyer.real_name", read_only=True)
    third_lawyer_name = serializers.CharField(source="third_lawyer.real_name", read_only=True)
    letters = LetterSerializer(many=True, read_only=True)
    introduces = IntroduceSerializer(many=True, read_only=True)
    progresses = CaseProgressSerializer(many=True, read_only=True)
    current_phase = serializers.SerializerMethodField()     # 当前案件阶段
    is_final = serializers.SerializerMethodField()          # 结案标志
    recvtime = serializers.SerializerMethodField()          # 接收时间
    lawyers = serializers.SerializerMethodField()          # 接收时间
    files = CaseFileSerializer(many=True, read_only=True)
    warning = serializers.SerializerMethodField()

    class Meta:
        model = Case
        exclude = ['recv_time', 'update_time', 'add_time']

    def get_current_phase(self, obj):
        phase = self.recent_phase(obj)
        if phase and phase.progress:
            return phase.progress.name
        return ""

    def get_is_final(self, obj):
        phase = self.recent_phase(obj)
        if phase and phase.progress:
            return phase.progress.is_final
        return False

    def recent_phase(self, obj):
        return obj.progresses.all().order_by("-add_time").first()

    def get_recvtime(self, obj):
        return datetime.datetime.strftime(obj.add_time, '%Y-%m-%d')

    def get_lawyers(self, obj):
        assist_lawyer_name = obj.assist_lawyer.real_name if obj.assist_lawyer else ""
        if obj.third_lawyer:
            third_lawyer_name = obj.third_lawyer.real_name
            if obj.assist_lawyer:
                lawyers = "{},{}".format(assist_lawyer_name, third_lawyer_name)
                return lawyers
            else:
                return third_lawyer_name
        else:
            return assist_lawyer_name

    def get_warning(self, obj):
        if obj.open_time:
            days = (obj.open_time - datetime.date.today()).days + 1
            if 7 >= days >= 0:
                return 1
        return 0


class ReasonSerializer(ModelSerializer):
    """
    案由
    """
    class Meta:
        model = Reason
        exclude = ['update_time', 'add_time']


class CriminalIntroduceSerializer(ModelSerializer):
    """
    刑事介绍函
    """
    user_name = serializers.CharField(source="user.real_name", read_only=True)

    class Meta:
        model = CriminalIntroduce
        exclude = ['update_time', 'add_time']

